<?php 
namespace My\Controller;

use Utuo\BackgroundController;

class ScorePointController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle("积分项管理");
		$this->setActionTitle(array(
			'index' => '积分项列表',
			'modify' => '积分项修改',
			'recycle' => '回收站',
			'add' => '积分项添加',
		));
		$this->setActionNav("index,add,recycle");
	}
	
	/**
	 * 积分项列表
	 * @param unknown $is_delectd
	 */
	public function getLists( $is_delectd ) {
		$condition = array( 'a.is_deleted' => $is_delectd, 'b.is_deleted' => 0 );
		$scorePointLists = D('ScorePoint a')->join("__SCORE_EVENT__ b on a.event_id=b.id ")->where($condition)->page($this->getPage(), $this->getPageSize())->field("a.*,b.name as eventName")->select();
		$count = D('ScorePoint a')->join("__SCORE_EVENT__ b on a.action_id=b.id")->where($condition)->count();
		$this->showPage($count, $this->getPageSize());
		$this->assign('scorePointLists', $scorePointLists);
		$this->display();
	}
	
	/**
	 * 添加积分项
	 */
	public function addAction() {
		$eventList = M("ScoreEvent")->where("1")->getField("id,name");
		$scorePoint = array();
		$scorePoint['eventOptions'] = $this->getOption($eventList, "", "==请选择触发条件==");
		$this->assign("scorePoint", $scorePoint);
		$this->display("save");
	}
	
	/**
	 * 修改积分项
	 */
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$eventList = M("ScoreEvent")->getField("id,name");
		$scorePoint= M("ScorePoint")->where("cid=%d", $this->aid)->find($id);
		$scorePoint['eventOptions'] = $this->getOption($eventList, $scorePoint['event_id'], "==请选择触发条件==");
		$this->assign("scorePoint", $scorePoint);
		$this->display("save");
	}
	
	/**
	 * 保存积分项
	 */
	public function saveAction() {
		$m = M("ScorePoint");
		if( $m->create() and $m->isCreated = true) {
			$n = clone $m;
			// 检查是否已添加或找回回收站内的记录
			if( empty($n->id) ) {
				$scorePoint = $n->where(array('event_id'=>$n->event_id, 'cid'=> $this->aid))->find();
				if( $scorePoint ) {
					if ( $scorePoint['is_deleted'] ) {
						$m->is_deleted = 0; // 还原
						$_REQUEST['id'] = $m->id = $scorePoint['id'];
					} else {
						$this->ajaxError("积分项已存在");
					}
				}
			} else {
				$scorePointCount = $n->where(array('event_id'=>$n->event_id, 'cid'=> $this->aid, 'id' => array('neq', $n->id)))->count() and $this->ajaxError("积分项已存在");
			}
			$this->submitPost($m);
		} else {
			$this->ajaxError($m->getError());
		}
	}
	
}

?>